package cn.tedu._05weibo.base.exception;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @Author Justin Parker
 * @Date 2024/8/13 0013 9:42
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandle(IllegalArgumentException ex){
        //ex.getMessage():获取异常消息
        String data = ex.getMessage();
        return JsonResult.fail(data);
    }

//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException ex){
//        String data = ex.getMessage();
//
//        return JsonResult.fail(data);
//
//    }

//    @ExceptionHandler
//    public JsonResult doHandleThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("Throwable"+data);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data );
//
//    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException
    (MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data );
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        //获取异常提示信息
        String data = ex.getMessage().split(": ")[1].trim();
        log.error("ConstraintViolationException"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data );
    }
}
